--Command Pattern
--[[
	命令模式：（行为型）
	作用：
	使用场景：
--]]

require 'Class'

CommandType = {
	battle1 = 1,
	battle2 = 2,
	sys = 3,
	NUM = 4,
}

CommandBase = Class()  --命令基类
CommandBase.key = nil  --自带key值，便于从table中移除
CommandBase.receiver = nil
CommandBase.Execute = function(self,context)end  --context 为环境上下文
BattleCommand = Class(CommandBase)  --战斗命令
BattleCommand.Execute = function(self,context)
	context.name = '战斗'
	print(string.format('需要执行战斗命令：%s',context.name))
	if self.receiver then
		self.receiver:Execute(context)
	end
end
SysCommand = Class(CommandBase)  --系统命令
SysCommand.Execute = function(self,context)
	context.name = '设置'
	print(string.format('需要执行系统命令：%s',context.name))
	if self.receiver then
		self.receiver:Execute(context)
	end
end

ReceiverBase = Class()  --Receiver 基类
ReceiverBase.Execute = function(self,context)end
GameRootReceiver = Class(ReceiverBase)  --Receiver 实现类
GameRootReceiver.Execute = function(self,context)
	print(string.format('GameRoot Receiver 执行命令：%s',context.name))
end

Invoker = Class()  --调用者
Invoker.containner = {}  --命令容器
Invoker.AddCommand = function(self,commandType,command)
	command.key = commandType
	self.containner[commandType] = command
end
Invoker.RemoveCommand = function(self,commandType)
	self.containner[commandType] = nil
end
Invoker.Execute = function(self,context)
	if not self.containner then return end
	for k,v in pairs(self.containner) do
		v:Execute(context)
	end
end

--------Main--------
function main()
	gameRootReceiver = GameRootReceiver:New()

	battleCommand1 = BattleCommand:New({receiver = gameRootReceiver})
	battleCommand2 = BattleCommand:New({receiver = gameRootReceiver})
	sysCommand = SysCommand:New({receiver = gameRootReceiver})

	invoker = Invoker:New()
	invoker:AddCommand(CommandType.battle1,battleCommand1)
	invoker:AddCommand(CommandType.battle2,battleCommand2)
	invoker:AddCommand(CommandType.sys,sysCommand)
	context = {name = '命令模式'}
	invoker:Execute(context)  --需要执行战斗命令：战斗
							  --GameRoot Receiver 执行命令：战斗
							  --需要执行战斗命令：战斗
							  --GameRoot Receiver 执行命令：战斗
							  --需要执行系统命令：设置
							  --GameRoot Receiver 执行命令：设置

	print('----')
	invoker:RemoveCommand(CommandType.battle1)
	invoker:Execute(context)
	print('----')
	invoker:RemoveCommand(CommandType.battle2)
	invoker:Execute(context)
	print('----')
	invoker:RemoveCommand(CommandType.sys)
	invoker:Execute(context)
	print(#invoker.containner)
end

main()
